﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WpfPractice.MVVM
{
    public class Messenger
    {
        private static readonly Messenger _instance = new Messenger();
        private readonly Dictionary<Type, Dictionary<string, Action<object>>> _registrations = new Dictionary<Type, Dictionary<string, Action<object>>>();

        public static Messenger Default => _instance;

        public void Register<TMessage>(string token, Action<object> action)
        {
            var messageType = typeof(TMessage);
            if (!_registrations.TryGetValue(messageType, out var tokenActions))
            {
                tokenActions = new Dictionary<string, Action<object>>();
                _registrations[messageType] = tokenActions;
            }
            tokenActions[token] = action;
        }

        public void Unregister<TMessage>(string token)
        {
            var messageType = typeof(TMessage);
            if (_registrations.TryGetValue(messageType, out var tokenActions))
            {
                tokenActions.Remove(token);
            }
        }

        public void Send<TMessage>(string token, TMessage message)
        {
            var messageType = typeof(TMessage);
            if (_registrations.TryGetValue(messageType, out var tokenActions) && tokenActions.TryGetValue(token, out var action))
            {
                action?.Invoke(message);
            }
        }
    }
    public class Message
    {
        public string Content { get; set; }
        // 可以添加其他需要传递的数据
    }
}
